package com.qd.p2p.web.action;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.qdlc.p2p.biz.service.AccountBankService;
import com.qdlc.p2p.biz.service.AccountLogService;
import com.qdlc.p2p.biz.service.AccountRechargeService;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.AdditionalUserDrawLotteryService;
import com.qdlc.p2p.biz.service.BorrowCollectionService;
import com.qdlc.p2p.biz.service.BorrowRepaymentService;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.BorrowTenderService;
import com.qdlc.p2p.biz.service.FinanFlowQueryService;
import com.qdlc.p2p.biz.service.MessageService;
import com.qdlc.p2p.biz.service.RateInterestService;
import com.qdlc.p2p.biz.service.UserCacheService;
import com.qdlc.p2p.biz.service.UserCreditService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserInviteService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.service.UserSignService;
import com.qdlc.p2p.biz.service.UserVipUpRateService;
import com.qdlc.p2p.biz.util.ActivityTools;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.code.BASE64Encoder;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.AccountBank;
import com.qdlc.p2p.dal.dto.AdditionalUserDrawLottery;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.dto.UserCredit;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.dto.UserSign;
import com.qdlc.p2p.dal.dto.UserVip;
import com.qdlc.p2p.dal.model.AccountLogModel;
import com.qdlc.p2p.dal.model.AccountModel;
import com.qdlc.p2p.dal.model.AccountRechargeModel;
import com.qdlc.p2p.dal.model.BorrowCollectionModel;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.model.BorrowRepaymentModel;
import com.qdlc.p2p.dal.model.UserInviteModel;
import com.qdlc.p2p.dal.util.UserTypeUtils;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 账户中心资金相关处理
 *
 * @version 2.0
 * @since 2014年6月17日
 */
@SuppressWarnings("rawtypes")
public class MemberAction extends BaseAction {

	@Resource
	private UserCreditService userCreditService;
	@Resource
	private AccountService accountService;
	@Resource
	private MessageService messageService;
	@Resource
	private BorrowTenderService borrowTenderService;
	@Resource
	private BorrowCollectionService borrowCollectionService;
	@Resource
	private UserService userService;
	@Resource
	private UserIdentifyService userIdentifyService;
	@Resource
	private UserCacheService userCacheService;
	@Resource
	private AccountBankService accountBankService;
	@Resource
	private BorrowRepaymentService borrowRepaymentService;
	@Resource
	private BorrowService borrowService;
	@Resource
	private AccountRechargeService accountRechargeService;
	@Resource
	private AccountLogService accountLogService;
	@Resource
	private UserInviteService userInviteService;
	@Resource
	private FinanFlowQueryService finanFlowQueryService;
	@Resource
	private RateInterestService rateInterestService;
	@Resource
	private UserVipUpRateService userVipUpRateService;
	@Resource
	private UserSignService userSignService;
	@Resource
	private AdditionalUserDrawLotteryService additionalUserDrawLotteryService;

	private User user;

	private Map<String, Object> data;

	private String  returnUrl;

	public String getReturnUrl() {
		return returnUrl;
	}

	/**
	 * 账户主页
	 * @return
	 * @throws Exception
	 */
	@Action(value="/member/main",results = { @Result(name = "main", type = "ftl", location = "/member/main.html"),
			@Result(name = "main_firm", type = "ftl", location = "/member_borrow/main.html"),
			@Result(name = "main_vouch", type = "ftl", location = "/member_guarantee/main.html")})
	public String main() throws Exception {
		user = getSessionUser();
		// 获得资金详情
		Account account = accountService.findAccountByUserId(user.getUserId());
		request.setAttribute("account", account);
		// 系统通知未读信息的总数
		int unreadCount = messageService.unreadCount(user.getUserId());
		request.setAttribute("unreadCount", unreadCount);

		// 银行卡数量
//		int bankAccount = accountBankService.count(user.getUserId());
//		request.setAttribute("bankAccount", bankAccount);
		UserCache uc = UserUtils.getUserCacheByUserId(user);
		if (uc.getUserType() == 3 || uc.getUserType() == 2) {
			return "main_firm";
		} else if (uc.getUserNature() == 3) {
			return "main_vouch";
	    }
		return "main";
	}

	/**
	 * 资金记录页面
	 * @return
	 * @throws Exception
	 */
	@Action("/member_borrow/account/log")
	public String accountLog() throws Exception {
		return "log";
	}
	/**
	 * 借款人修改头像页面
	 * @return
	 * @throws Exception
	 */
	@Action(value="/member_borrow/info/face",results = { @Result(name = "face", type = "ftl", location = "/member_${returnUrl}/info/face.html")})
	public String face() throws Exception {
		 int flag=paramInt("flag");
		 if(flag == 1){
			setReturnUrl("guarantee");
		 }else{
			 setReturnUrl("borrow");
		 }
		 return "face";
	}

	/**
	 * 站内信息页面
	 * @return
	 * @throws Exception
	 */
	@Action("/member_borrow/message/detail")
	public String detail() throws Exception {
		return "detail";
	}

	@Action("/member/infoJson")
	public void infoJson() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		UserCache userCache = UserUtils.getUserCacheByUserId(user.getUserId());
		data.put("companyName", userCache.getCompanyName());
		data.put("companyRegNo", userCache.getCompanyRegNo());
		data.put("taxRegNo", userCache.getTaxRegNo());
		printWebJson(getStringOfJpaObj(data));
	}

	/*****************************商家个人中心显示数据 start**********************************/

	/**
	 * 开通第三方账号之后的数据
	 * @throws Exception
	 */
	@Action("/member_borrow/security/realNameJson")
	public void realNameJson() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		data.put("realName", user.getRealName());
		data.put("cardId", user.getCardId());
		data.put("mobilePhone", user.getMobilePhone());
		printWebJson(getStringOfJpaObj(data));
	}

	/**
	 * 后台开户后，第一次登录修改登录密码
	 * @return
	 * @throws Exception
	 */
	@Action("/member_borrow/changeLoginPwd")
	public String changeLoginPwd() throws Exception {
		return "changeLoginPwd";
	}

	/**
	 * 提现
	 * @return
	 * @throws Exception
	 */
	@Action("/member_borrow/recharge/log")
	public String rechargeLog() throws Exception {
		AccountRechargeModel recharge = accountRechargeService.getRechargeSummary(getSessionUser().getUserId());
		Account account = accountService.findAccountByUserId(this.getSessionUserId());
		request.setAttribute("recharge", recharge);
		request.setAttribute("account", account);
		return "log";
	}

	/**
	 * 商家(借款人)招标中项目
	 * @throws Exception
	 */
	@Action("/member_borrow/businessBid")
	public String businessBid() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		BorrowModel model = new BorrowModel();
		model.setUser(user);
		model.setRows(4);
		model.setStatus(1);
		PageDataList<BorrowModel> page = borrowService.getList(model);
		data.put("businessBidList", page.getList());
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 商家(借款人)还款中项目
	 * @throws Exception
	 */
	@Action("/member_borrow/businessRepayment")
	public String businessRepayment() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		List<BorrowModel> businessRepaymentList = borrowService.businessRepayment(user);
		data.put("businessRepaymentList", businessRepaymentList);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 商家(借款人)更新用户认证状态
	 * @throws Exception
	 */
	@Action("/member_borrow/businessUserIdentify")
	public String businessUserIdentify() throws Exception {
		data = new HashMap<String, Object>();
		UserIdentify userIdentify = userIdentifyService.findById(getSessionUserId());
		user = getSessionUser();
		user = userService.find(user.getUserId());
		UserCache uc = userCacheService.findByUserId(user.getUserId());
		// 系统通知未读信息的总数
		int unReadCount = messageService.unreadCount(user.getUserId());
		data.put("userId", UserUtils.getUserCacheByUserId(user).getId());
		data.put("unReadCount", unReadCount);
		data.put("emailStatus", userIdentify.getEmailStatus());
		data.put("mobilePhoneStatus", userIdentify.getMobilePhoneStatus());
		data.put("realNameStatus", userIdentify.getRealNameStatus());
		data.put("companyName", uc.getCompanyName());
		data.put("email", user.getEmail());
		data.put("userName", user.getUserName());
		data.put("realName", user.getRealName());
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		int tppStatus = StringUtils.isBlank(tppUserCustId) ? 0 : 1;
		data.put("tppStatus", tppStatus);
		data.put("tpp_login_url", SystemConfigHelper.getValue(Nid.LOGIN_URL));
		data.put("userNature",uc.getUserNature());
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 商家(借款人)可提现余额 正在借款项目个数 正在借款金额 下一个待还日期信息
	 * @throws Exception
	 */
	@Action("/member_borrow/businessHandleMoney")
	public String businessHandleMoney() throws Exception {
		data = new HashMap<String, Object>();
		user = getSessionUser();
		//用户签到抽奖记录
		int signStatus = isSignLottery();
		data.put("signStatus", signStatus);
		// 获得信用额度
		UserCredit amount = userCreditService.findByUserId(user.getUserId());
		data.put("amount", amount);
		//可提现余额
		Account account = accountService.findAccountByUserId(user.getUserId());
		data.put("account", account);
		//正在借款项目信息
		int count = borrowService.findByStatusAndUserId(user.getUserId(), 1, 0);
		data.put("count", count);
		double total = borrowService.findAccountTotalByStatus(user.getUserId(), 1, 0);
		data.put("total", total);
		//待还的统计
		BorrowRepaymentModel brm = borrowRepaymentService.getReapyStatistics(user.getUserId());
		data.put("borrowRepay", brm);
		//待还总额 待还总项目
		int repaymentCount = borrowService.findByStatusAndUserId(user.getUserId(), 6, 7);
		data.put("repaymentCount", repaymentCount);
	  //double repaymentTotal = borrowService.findAccountTotalByStatus(user.getUserId(), 6, 7);
		double repaymentTotal = borrowRepaymentService.getUserBorrowRepayTotal(user.getUserId());
		data.put("repaymentTotal", repaymentTotal);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 交易记录
	 * @throws Exception
	 */
	@Action("/member_borrow/accountTransactionLog")
	public String accountTransactionLog() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		List<AccountLogModel> accountLogList = accountLogService.accountTransactionLog(user.getUserId());
		data.put("accountLogList", accountLogList);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 公司主页
	 * @return
	 * @throws Exception
	 */
	@Action("/member_borrow/home")
	public String home() throws Exception {
		String id = request.getParameter("id");
		request.setAttribute("id", id);
		user = getSessionUser();
		UserCache uc;
		if ("undefined".equals(id) || id == null) {
			uc = userCacheService.findByUserId(user.getUserId());
		} else {
			uc = userCacheService.findById(Long.parseLong(id));
		}
		if (uc == null || uc.getUserNature() != 2) {
			throw new UserException("用户不存在或不是企业用户");
		}
		return "home";
	}

	/**
	 * 公司主页动态数据
	 * @return
	 * @throws Exception
	 */
	@Action("/member_borrow/companyHomeJson")
	public String companyHomeJson() throws Exception {
		data = new HashMap<String, Object>();
		user = getSessionUser();
		UserCache uc;
		String id = request.getParameter("id");
		if ("undefined".equals(id)) {
			uc = userCacheService.findByUserId(user.getUserId());
			data.put("flag", true);
		} else {
			uc = userCacheService.findById(Long.parseLong(id));
		}
		String companyName = uc.getCompanyName();
		if (companyName.length() > 5) {
			uc.setCompanyName(companyName.substring(0, 2)+"****"+companyName.substring(companyName.length()-4));
		}
		String companyRegNo = uc.getCompanyRegNo();
		uc.setCompanyRegNo(companyRegNo.charAt(0)+"****"+companyRegNo.charAt(companyRegNo.length()-1));
		String taxRegNo = uc.getTaxRegNo();
		uc.setTaxRegNo(taxRegNo.charAt(0)+"****"+taxRegNo.charAt(taxRegNo.length()-1));
		String companyPhone = uc.getCompanyPhone();
		if (companyPhone != null && companyPhone.length() > 5) {
			uc.setCompanyPhone(companyPhone.substring(0, 4)+"****"+companyPhone.substring(companyRegNo.length()-2));
		}
		String companyFax = uc.getCompanyFax();
		if (companyFax != null && companyFax.length() > 5) {
			uc.setCompanyFax(companyFax.substring(0, 4)+"****"+companyFax.substring(companyFax.length()-2));
		}
		String companyEmail = uc.getCompanyEmail();
		if (companyEmail != null && !"".equals(companyEmail)) {
			uc.setCompanyFax("****"+companyFax.substring(companyFax.lastIndexOf("@")));
		}
		User u = UserUtils.getUserById(uc.getUserId());
		String realName = u.getRealName();
		if(realName!=null && realName.length()>0){
			u.setRealName(realName.charAt(0)+"**");
		}
		String mobilePhone = u.getMobilePhone();
		u.setMobilePhone(mobilePhone.substring(0,2)+"****"+mobilePhone.substring(mobilePhone.length()-2));
		String email = u.getEmail();
		u.setEmail("****"+email.substring(email.lastIndexOf("@")));
		data.put("uc", uc);
		data.put("url", SystemConfigHelper.getValue(Nid.MANAGE_URL));
		data.put("realName", u.getRealName());
		data.put("email", u.getEmail());
		data.put("mobilePhone", u.getMobilePhone());
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/*****************************商家个人中心显示数据 end**********************************/


	/*****************************投资者个人中心显示数据 start**********************************/

	/**
	 * 投资人 用户认证状态
	 * @throws Exception
	 */
	@Action("/member/investIdentify")
	public String investIdentify() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		UserIdentify userIdentify = userIdentifyService.findByUserId(getSessionUserId());
		UserCache cache = userCacheService.findByUserId(user.getUserId());
		//TODO:UserIdentify
//		session.put(Constant.SESSION_USER_IDENTIFY, userIdentify);
		user = userService.find(user.getUserId());
		// 系统通知未读信息的总数
		int unReadCount = messageService.unreadCount(user.getUserId());
		data.put("unReadCount", unReadCount);
		data.put("emailStatus", userIdentify.getEmailStatus());
		data.put("realNameStatus", userIdentify.getRealNameStatus());
		data.put("mobilePhoneStatus", userIdentify.getMobilePhoneStatus());
		//data.put("vipStatus", userIdentify.getVipStatus());
		data.put("userName", user.getUserName());
		data.put("email", user.getEmail());
		data.put("realName", user.getRealName());
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		int tppStatus = StringUtils.isBlank(tppUserCustId) ? 0 : 1;
		data.put("tppStatus", tppStatus);
		data.put("userType", cache.getUserType());
		data.put("tpp_login_url", SystemConfigHelper.getValue(Nid.LOGIN_URL));
		UserVip uservVip = UserUtils.getUserVipByUserId(user.getUserId());
		int level = 0;
		if (uservVip != null) {
			level = uservVip.getUserVipLevel().getLevel();
		}
		data.put("vipLevel", level);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 资产统计页面
	 * @return
	 * @throws Exception
	 */
	@Action(value="/member/account/assets",results = { @Result(name = "assets", type = "ftl", location = "/member/account/assets.html"),
			@Result(name = "assets_standard", type = "ftl", location = "/member_standard/account/assets.html")})
	public String assets() throws Exception {
		user = getSessionUser();
		Account account = accountService.findAccountByUserId(user.getUserId());
		request.setAttribute("account", account);
		/*//统计标待收利息 - 已转出利息
		double interest = borrowCollectionService.getInterestByUser(user);
		//统计标待收本金 - 已转出本金
		double capital = borrowCollectionService.getCapitalByUser(user);
		//统计债权待收本金、利息
		Object[] obj = bondCollectionService.getSumBondCollection(user.getUserId());
		double bondCapital = 0;
		double bondInterest = 0;
		if(obj!=null && obj.length==2){
			if(obj[0]!=null){
				bondCapital = Double.parseDouble(obj[0].toString());
			}
			if(obj[1]!=null){
				bondInterest = Double.parseDouble(obj[1].toString());
			}
		}
		Object[] flowObj = finanFlowQueryService.getFlowCollectionByUserId(user.getUserId());
		double flowCapital = 0;
		double flowInterest = 0;
		if(flowObj!=null && flowObj.length==2){
			if(flowObj[0]!=null){
				flowCapital = Double.parseDouble(flowObj[0].toString());
			}
			if(flowObj[1]!=null){
				flowInterest = Double.parseDouble(flowObj[1].toString());
			}
		}
		request.setAttribute("interest", BigDecimalUtil.add(BigDecimalUtil.add(interest,bondInterest),flowInterest));
		request.setAttribute("capital", BigDecimalUtil.add(BigDecimalUtil.add(capital,bondCapital),flowCapital));*/
		List<String> dates = borrowCollectionService.getCollectionDate(user);
		if(dates == null || dates.size() <= 0){
			dates.add(DateUtil.dateStr(DateUtil.getNow(), "yyyy-MM"));
		}
		request.setAttribute("dates", dates);

		return "assets";
	}
	/**
	 * 待收利息JSON
	 * @throws Exception
	 */
	@Action("/member/account/interestJson")
	public void interestJson() throws Exception {
		data = new HashMap<String, Object>();
		user = getSessionUser();
		String date = paramString("date");
		//正常投标待收
		List<Object[]> list = borrowCollectionService.getInterestByUserAndDate(user,date);
		List<Object> days = new ArrayList<Object>();
		List<Object> values = new ArrayList<Object>();
		for (Object[] o : list){
			days.add(o[0]);
			values.add(o[1]);
		}

		//流转理财待收
		List<Object[]> flowList = finanFlowQueryService.getFlowInterestByUserAndDate(user, date);
		List<Object> flowDays = new ArrayList<Object>();
		List<Object> flowValues = new ArrayList<Object>();
		for (Object[] o : flowList){
			flowDays.add(o[0]);
			flowValues.add(o[1]);
		}

		//加息券待收
		List<Object[]> rateList = rateInterestService.getRateCollectionInterest(user, date);
		List<Object> rateDays = new ArrayList<Object>();
		List<Object> rateValues = new ArrayList<Object>();
		for (Object[] o : rateList){
			rateDays.add(o[0]);
			rateValues.add(o[1]);
		}

		//vip加息待收
		List<Object[]> vipRateList = userVipUpRateService.getVipUpRateCollectionInterest(user, date);
		List<Object> vipRateDays = new ArrayList<Object>();
		List<Object> vipRateValues = new ArrayList<Object>();
		for (Object[] o : vipRateList){
			vipRateDays.add(o[0]);
			vipRateValues.add(o[1]);
		}


		List<String> numList = this.getDateNum(date);
		for(int i = 0; i < numList.size(); i++ ){
			String str = numList.get(i);
			if(!days.contains(str)){
				days.add(i,str);
				values.add(i,0);
			}

			if(!flowDays.contains(str)){
				flowDays.add(i,str);
				flowValues.add(i,0);
			}

			if(!rateDays.contains(str)){
				rateDays.add(i,str);
				rateValues.add(i,0);
			}
			if(!vipRateDays.contains(str)){
				vipRateDays.add(i,str);
				vipRateValues.add(i,0);
			}
		}

		data.put("day", days.toArray());
		data.put("value", values.toArray());
		data.put("flowValues", flowValues.toArray());
		data.put("rateValues", rateValues.toArray());
		data.put("vipRateValues", vipRateValues.toArray());
		printWebJson(getStringOfJpaObj(data));
	}

	/**
	 * 待收本金JSON
	 * @throws Exception
	 */
	@Action("/member/account/capitalJson")
	public void capitalJson() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		user = getSessionUser();
		//正常投标待收
		List<Object[]> list = borrowCollectionService.getCapitalByUserAndDate(user,date);
		List<Object> days = new ArrayList<Object>();
		List<Object> values = new ArrayList<Object>();
		for (Object[] o : list){
			days.add(o[0]);
			values.add(o[1]);
		}
		//流转理财待收
		List<Object[]> flowList = finanFlowQueryService.getFlowCapitalByUserAndDate(user, date);
		List<Object> flowDays = new ArrayList<Object>();
		List<Object> flowValues = new ArrayList<Object>();
		for (Object[] o : flowList){
			flowDays.add(o[0]);
			flowValues.add(o[1]);
		}

		List<String> numList = this.getDateNum(date);
		for(int i = 0; i < numList.size(); i++ ){
			String str = numList.get(i);
			if(!days.contains(str)){
				days.add(i,str);
				values.add(i,0);
			}

			if(!flowDays.contains(str)){
				flowDays.add(i,str);
				flowValues.add(i,0);
			}
		}

		data.put("day", days.toArray());
		data.put("value", values.toArray());
		data.put("flowValues", flowValues.toArray());
		printWebJson(getStringOfJpaObj(data));
	}
	/**
	 * 资金统计信息
	 * @throws Exception
	 */
	@Action("/member/investHandleMoney")
	public String investHandleMoney() throws Exception {
		data = new HashMap<String, Object>();
		user = getSessionUser();
		int signStatus = isSignLottery();
		data.put("signStatus", signStatus);
		Account account = accountService.findAccountByUserId(user.getUserId());
		data.put("account", account);
		//今日净收益
		double todayEarnAmount = accountLogService.todayEarnAmount(user.getUserId());
		data.put("todayEarnAmount", todayEarnAmount);
		//累计净收益
		double earnAmount = accountLogService.earnAmount(user.getUserId());
		data.put("earnAmount", earnAmount);
		//在投金额
		double investIngAmount = borrowTenderService.investIngAmount(user.getUserId());
		data.put("investIngAmount", investIngAmount);
		//累计投资
		double investAmount = borrowTenderService.investAmount(user.getUserId());
		data.put("investAmount", investAmount);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

    @Action("/member/getSignStatus")
    public String getSignStatus() throws Exception {
        int signStatus = isSignLottery();
        data.put("signStatus", signStatus);
		printWebJson(getStringOfJpaObj(data));
        return null;
    }

	/**
	 * 可投借款标
	 * @return
	 * @throws Exception
	 */
	@Action("/member/investList")
	public String investList() throws Exception{
		data = new HashMap<String, Object>();
		user = getSessionUser();
		List<BorrowModel> list = borrowService.investList(user);
		data.put("list", list);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 收款（3条）
	 * @return
	 * @throws Exception
	 */
	@Action("/member/investCollectionList")
	public String investCollectionList() throws Exception{
		user = getSessionUser();
		List<BorrowCollectionModel> list = borrowCollectionService.investCollectionList(user);
		data = new HashMap<String, Object>();
		data.put("data", list);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 交易记录
	 * @throws Exception
	 */
	@Action("/member/investTransactionLog")
	public String investTransactionLog() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		List<AccountLogModel> accountLogList = accountLogService.accountTransactionLog(user.getUserId());
		data.put("accountLogList", accountLogList);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 投资者通过投标详情跳转到借款人的公司主页
	 * @return
	 * @throws Exception
	 */
	@Action("/member/borrowHome")
	public String borrowHome() throws Exception {
		return "home";
	}

	/**
	 * 公司主页动态数据
	 * @return
	 * @throws Exception
	 */
	@Action("/member/companyHome")
	public String companyHome() throws Exception {
		data = new HashMap<String, Object>();
		long id = paramLong("id");
		UserCache uc = userCacheService.findById(id);
		data.put("uc", uc);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/*****************************投资者个人中心显示数据 end**********************************/











	/**
	 * 待收 json数据
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/member/repayCollectJson")
	public String repayCollectJson() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		// 待收的统计
		BorrowCollectionModel bcm = borrowCollectionService.getCollectStatistics(user.getUserId());
		data.put("borrowCollect", bcm);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 用户待收金额信息
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/member/getUserCollectionAccount")
	public String getUserCollectionAccount() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		// 用户待收金额信息
		Account account = accountService.findAccountByUserId(user.getUserId());
		AccountModel accountModel = AccountModel.instance(account);
		accountModel.setUser(null);
		data.put("accountModel", accountModel);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}

	/**
	 * 用户已赚金额信息
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/member/getUserEarnedAccount")
	public String getUserEarnedAccount() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		long userId = user.getUserId();
		// 已赚利息
		double receivedInterestSum = borrowCollectionService.getReceivedInterestSum(userId);
		// 已赚奖励
//		AccountSum accountSum = accountSumService.findByUserId(userId);
		data.put("receivedInterestSum", receivedInterestSum);
//		data.put("award", accountSum.getAward());
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 获取月份的所有天数
	 * @param time 月份，格式必须为yyyy-MM
	 * @return 月份的天数
	 */
	private List<String> getDateNum(String time){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			Date date = sdf.parse(time);
			Calendar a = Calendar.getInstance();
			a.setTime(date);
			a.set(Calendar.DATE, 1);
			a.roll(Calendar.DATE, -1);
			int num = a.get(Calendar.DATE);
			List<String> list = new ArrayList<String>();
			for(int i = 0; i < num; i++){
				Date j = DateUtil.rollDay(date, i);
				list.add(DateUtil.dateStr8(j));
			}
			return list;
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 邀请好友页面
	 * @return
	 * @throws IOException
	 */
	@Action("/member/friend/userInvite")
	public String userInvite() throws IOException {
		user = getSessionUser();
		//checkInvestUser();
		byte[] bytes = (user.getUserId()+"").getBytes("utf-8");
		BASE64Encoder encoder = new BASE64Encoder();
		request.setAttribute("ui", encoder.encode(bytes));
		return "userInvite";
	}
	/**
	 * 邀请好友数据
	 * @return
	 * @throws IOException
	 */
	@Action("/member/friend/userInviteJSON")
	public void userInviteJSON() throws IOException {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		PageDataList<UserInviteModel> list = userInviteService.findByInviteUser(user, paramInt("page"));
		data.put("data", list);
		printWebJson(getStringOfJpaObj(data));
	}

	/**
	 * 判断用户是否可以签到
	 *
	 * @return
	 */
	public int isSignLottery() throws Exception {
		data = new HashMap<String, Object>();
		User user = getSessionUser();
		if (user == null) {
			throw new UserException("请登录", BusinessException.TYPE_JSON);
		}

		UserSign userSign = userSignService.findLastRecord(user.getUserId());
        if(userSign == null || !ActivityTools.getCurrentDate().equals(ActivityTools.format(userSign.getSignTime()))) {
            return 0;
            // 签到抽奖状态：1已签到未抽奖，2已抽奖，0未签到
            // 今天已经签到：再判断是否已经抽奖
        } else {
			// 判断有没有抽奖机会，就算不是今天的也可以
			AdditionalUserDrawLottery additionalUserDrawLottery = additionalUserDrawLotteryService.getValidDrawLotteryByUserId(user.getUserId());
            return additionalUserDrawLottery.getId() != 0? 1:2;
		}
	}
	
	/**
	 * 检测账户是否绑定银行卡，如果绑定银行卡，检测是否绑定手机号码。
	 * @throws IOException
	 */
	@Action("/member/bank/checkBinding")
	public void hasBindingBank() throws IOException{
		User user = getSessionUser();
		if (user == null) {
			throw new UserException("请登录", BusinessException.TYPE_JSON);
		}
		//企业账户可以不进行绑卡验证
		if(UserTypeUtils.isInvestmentBorrow(user.getUserId())){
			printWebSuccess();
		}else{
			Map<String, Object> extraMap = new HashMap<String, Object>();
			List<AccountBank> bankList = accountBankService.list(user.getUserId());
			if(CollectionUtils.isEmpty(bankList)){
				extraMap.put("error_type", "no_bank");
				printWebResult("请绑定银行卡！", false, extraMap);
				return;
			}
			
			boolean bindPhone = false;
			for(AccountBank bank: bankList){
				if(StringUtils.isNotEmpty(bank.getMobilephone())){
					bindPhone = true;
					break;
				}
			}
			if(bindPhone){
				printWebSuccess();
			}else{
				extraMap.put("error_type", "no_phone");
				printWebResult("请为银行卡绑定手机号码！", bindPhone, extraMap);
			}
		}
	}
}
